package com.jgit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 对象存储：负责Git对象的存储和读取
 * 对象存储在 .git/objects/ 目录下，使用SHA-1的前两位作为子目录名
 */
public class ObjectStore {
    private String gitDir;
    
    public ObjectStore(String gitDir) {
        this.gitDir = gitDir;
    }
    
    /**
     * 存储对象到文件系统
     */
    public void store(GitObject obj) throws IOException {
        if (obj.getHash() == null) {
            obj.calculateHash();
        }
        
        String hash = obj.getHash();
        String dirName = hash.substring(0, 2);
        String fileName = hash.substring(2);
        
        Path objectDir = Paths.get(gitDir, "objects", dirName);
        Files.createDirectories(objectDir);
        
        Path objectFile = objectDir.resolve(fileName);
        
        // 如果对象已存在，跳过
        if (Files.exists(objectFile)) {
            return;
        }
        
        byte[] compressed = obj.compress();
        Files.write(objectFile, compressed);
    }
    
    /**
     * 从文件系统读取对象
     */
    public GitObject read(String hash) throws IOException {
        String dirName = hash.substring(0, 2);
        String fileName = hash.substring(2);
        
        Path objectFile = Paths.get(gitDir, "objects", dirName, fileName);
        
        if (!Files.exists(objectFile)) {
            throw new IOException("Object not found: " + hash);
        }
        
        byte[] compressed = Files.readAllBytes(objectFile);
        return GitObject.decompress(compressed);
    }
    
    /**
     * 检查对象是否存在
     */
    public boolean exists(String hash) {
        String dirName = hash.substring(0, 2);
        String fileName = hash.substring(2);
        Path objectFile = Paths.get(gitDir, "objects", dirName, fileName);
        return Files.exists(objectFile);
    }
}

